package TimedTasks

import (
	"Student_Mental/DBconfing"
	"Student_Mental/controller/wsService"
	"encoding/json"
	"fmt"
	"time"
)

func WriteRides() {
	//定时任务 10s
	ticker := time.NewTicker(3600 * time.Second)
	for {
		select {
		case <-ticker.C:
			ridesWriteMsqlOfMessageList()
		}
	}
}

// ridesWriteMsqlOfMessageList 把redis中的messageList记录写入mysql
func ridesWriteMsqlOfMessageList() {
	red, _ := DBconfing.ConnRedis()
	sql, _ := DBconfing.Mysql()
	defer red.Close()
	defer sql.Close()
	M := wsService.Message{}
	// 获取长度
	listLength, err := red.LLen("messageList").Result()
	if err != nil {
		panic(err)
	}
	fmt.Println(listLength)
	if listLength >= 1 {
		// 从 Redis 中读取数据
		messages, err := red.LRange("messageList", 0, -1).Result()
		tx, err := sql.Begin() //开始事务
		if err != nil {
			fmt.Println(err)
		}
		// 在 mysql 中插入数据
		for i := len(messages) - 1; i >= 0; i-- {
			data := messages[i]
			json.Unmarshal([]byte(data), &M)
			_, err := tx.Exec("INSERT INTO message (roomId, sender,senderName,recipient,content,sendTime,type,SendTimestamp) VALUES (?,?,?,?,?,?,?,?)", M.RoomId, M.Sender, M.SenderName, M.Recipient, M.Content, M.SendTime, M.Type, M.SendTimestamp)
			if err != nil {
				tx.Rollback()
				fmt.Println(err)
			}
		}
		// 提交事务
		err = tx.Commit()
		if err != nil {
			tx.Rollback()
			fmt.Println(err)
			return
		}
		err = red.Del("messageList").Err() //删除
		if err != nil {
			fmt.Println(err)
			return
		}
		println("redis成功写入mysql")
	}
}
